import 'package:flutter/material.dart';
import '../models/ddl_item.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/github.dart';
import '../pages/code_input_page.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:flutter/services.dart';
import '../app_data_manager.dart';

class _AttachmentInfo {
  final String name;
  final String size;
  final String url;
  _AttachmentInfo({required this.name, required this.size, required this.url});
}

class DDLDetailPage extends StatefulWidget {
  final DDLItem item;
  final Function(DDLItem) onUpdate;

  const DDLDetailPage({
    super.key,
    required this.item,
    required this.onUpdate,
  });

  @override
  _DDLDetailPageState createState() => _DDLDetailPageState();
}

class _DDLDetailPageState extends State<DDLDetailPage> {
  late DDLItem _editingItem;
  bool _isEditing = false;
  final _formKey = GlobalKey<FormState>();
  
  late TextEditingController _titleController;
  late TextEditingController _descriptionController;

  // 添加支持的编程语言列表
  final List<String> _programmingLanguages = [
    'dart', 'python', 'javascript', 'java', 'cpp', 'c', 'csharp',
    'go', 'rust', 'swift', 'kotlin', 'ruby', 'php', 'html', 'css',
    'sql', 'shell', 'yaml', 'json', 'xml', 'markdown'
  ];

  static const int _maxFileSize = 5 * 1024 * 1024; // 5MB in bytes
  
  final List<_AttachmentInfo> _attachments = [];

  Future<String?> _saveFileToLocal(File sourceFile, String prefix) async {
    try {
      if (await sourceFile.length() > _maxFileSize) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('文件大小超过5MB限制')),
        );
        return null;
      }

      final appDir = await getTemporaryDirectory(); // 实际就是 /data/data/包名/files
      final storageDir = Directory('${appDir.path}/attachments');
      if (!await storageDir.exists()) {
        await storageDir.create(recursive: true);
      }
      final fileName = '${prefix}_${DateTime.now().millisecondsSinceEpoch}_${sourceFile.path.split('/').last}';
      final targetPath = '${storageDir.path}/$fileName';
      
      await sourceFile.copy(targetPath);
      print('保存文件成功: $targetPath');
      return 'file://$targetPath';
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存文件失败: $e')),
      );
      return null;
    }
  }

  @override
  void initState() {
    super.initState();
    _editingItem = widget.item.copyWith();
    _titleController = TextEditingController(text: _editingItem.title);
    _descriptionController = TextEditingController(text: _editingItem.description ?? '');
    
    // 确保起始日期和截止日期都不为空
    if (_editingItem.startDate == null) {
      _editingItem = _editingItem.copyWith(startDate: DateTime.now());
    }
    if (_editingItem.deadline == null) {
      _editingItem = _editingItem.copyWith(deadline: DateTime.now().add(const Duration(days: 1)));
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () async {
            // 如果正在编辑，先保存更改
            if (_isEditing) {
              if (_formKey.currentState!.validate()) {
                await _saveChanges();
              }
            }
            // 通知父组件更新并返回
            widget.onUpdate(_editingItem);
            if (mounted) {
              Navigator.of(context).pop();
            }
          },
        ),
        title: const Text('DDL详情'),
        actions: [
          IconButton(
            icon: Icon(_isEditing ? Icons.check : Icons.edit),
            onPressed: () {
              if (_isEditing) {
                if (_formKey.currentState!.validate()) {
                  _saveChanges();
                }
              } else {
                setState(() {
                  _isEditing = true;
                });
              }
            },
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            _buildTextField(
              label: '标题',
              controller: _titleController,
              enabled: _isEditing,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入标题';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            _buildDateTimePicker(
              label: '截止日期',
              value: _editingItem.deadline,
              onChanged: _isEditing
                  ? (date) {
                      if (date != null) {
                        setState(() {
                          _editingItem = _editingItem.copyWith(deadline: date);
                        });
                      }
                    }
                  : null,
            ),
            const SizedBox(height: 16),
            _buildDateTimePicker(
              label: '开始日期（可选）',
              value: _editingItem.startDate,
              onChanged: _isEditing
                  ? (date) {
                      setState(() {
                        _editingItem = _editingItem.copyWith(startDate: date);
                      });
                    }
                  : null,
              allowNull: true,
            ),
            const SizedBox(height: 16),
            _buildDescriptionSection(),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField({
    required String label,
    required TextEditingController controller,
    bool enabled = true,
    int? maxLines,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      enabled: enabled,
      maxLines: maxLines,
      decoration: InputDecoration(
        labelText: label,
        border: const OutlineInputBorder(),
        enabled: enabled,
      ),
      validator: validator ?? (value) {
        if (value == null || value.isEmpty) {
          return '请输入$label';
        }
        return null;
      },
    );
  }

  Widget _buildDateTimePicker({
    required String label,
    required DateTime? value,
    required Function(DateTime?)? onChanged,
    bool allowNull = false,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            color: Colors.grey,
          ),
        ),
        const SizedBox(height: 8),
        InkWell(
          onTap: onChanged == null
              ? null
              : () async {
                  final date = await showDatePicker(
                    context: context,
                    initialDate: value ?? DateTime.now(),
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2100),
                  );
                  if (date != null) {
                    final time = await showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.fromDateTime(
                        value ?? DateTime.now(),
                      ),
                    );
                    if (time != null) {
                      final dateTime = DateTime(
                        date.year,
                        date.month,
                        date.day,
                        time.hour,
                        time.minute,
                      );
                      
                      // 如果是截止日期，检查是否晚于起始日期
                      if (label == '截止日期' && _editingItem.startDate != null) {
                        if (dateTime.isBefore(_editingItem.startDate!)) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('截止日期必须晚于起始日期')),
                          );
                          return;
                        }
                      }
                      
                      // 如果是起始日期，检查是否早于截止日期
                      if (label == '开始日期（可选）' && _editingItem.deadline != null) {
                        if (dateTime.isAfter(_editingItem.deadline!)) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('起始日期必须早于截止日期')),
                          );
                          return;
                        }
                      }
                      
                      onChanged(dateTime);
                    }
                  } else if (allowNull) {
                    onChanged(null);
                  }
                },
          child: Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 12,
              vertical: 16,
            ),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  value == null
                      ? '未设置'
                      : '${value.year}年${value.month}月${value.day}日 ${value.hour}:${value.minute.toString().padLeft(2, '0')}',
                ),
                if (_isEditing)
                  Icon(
                    Icons.calendar_today,
                    color: Colors.grey[600],
                  ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDescriptionSection() {
    if (_isEditing) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '详细描述（支持Markdown格式）',
            style: TextStyle(fontSize: 16, color: Colors.grey),
          ),
          const SizedBox(height: 8),
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Column(
              children: [
                TextField(
                  controller: _descriptionController,
                  maxLines: 8,
                  onChanged: (value) {
                    setState(() {});
                  },
                  decoration: const InputDecoration(
                    contentPadding: EdgeInsets.all(16),
                    border: InputBorder.none,
                    hintText: '在这里输入详细描述...',
                  ),
                ),
                Divider(height: 1, color: Colors.grey[300]),
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: [
                      IconButton(
                        icon: const Icon(Icons.format_bold),
                        onPressed: () => _insertMarkdown('**', '**'),
                        tooltip: '粗体',
                      ),
                      IconButton(
                        icon: const Icon(Icons.format_italic),
                        onPressed: () => _insertMarkdown('*', '*'),
                        tooltip: '斜体',
                      ),
                      IconButton(
                        icon: const Icon(Icons.format_list_bulleted),
                        onPressed: () => _insertMarkdown('\n- ', ''),
                        tooltip: '无序列表',
                      ),
                      IconButton(
                        icon: const Icon(Icons.format_list_numbered),
                        onPressed: () => _insertMarkdown('\n1. ', ''),
                        tooltip: '有序列表',
                      ),
                      IconButton(
                        icon: const Icon(Icons.link),
                        onPressed: _showInsertLinkDialog,
                        tooltip: '链接',
                      ),
                      IconButton(
                        icon: const Icon(Icons.image),
                        onPressed: _insertImage,
                        tooltip: '插入图片',
                      ),
                      IconButton(
                        icon: const Icon(Icons.code),
                        onPressed: _insertCode,
                        tooltip: '插入代码',
                      ),
                      IconButton(
                        icon: const Icon(Icons.attach_file),
                        onPressed: _insertAttachment,
                        tooltip: '附件',
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          const Text(
            'Markdown 预览',
            style: TextStyle(fontSize: 16, color: Colors.grey),
          ),
          const SizedBox(height: 8),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(4),
            ),
            child: MarkdownBody(
              data: _descriptionController.text,
              selectable: true,
              syntaxHighlighter: _CodeHighlighter(),
            ),
          ),
          ..._buildAttachmentCards(editable: true),
        ],
      );
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (_editingItem.description?.isNotEmpty == true) ...[
            const SizedBox(height: 24),
            const Text(
              '详细描述',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                border: Border.all(color: Colors.grey[300]!),
                borderRadius: BorderRadius.circular(4),
              ),
              child: MarkdownBody(
                data: _editingItem.description!,
                selectable: true,
              ),
            ),
          ],
          ..._buildAttachmentCards(editable: false),
        ],
      );
    }
  }

  Future<void> _saveChanges() async {
    // 验证日期
    if (_editingItem.startDate == null || _editingItem.deadline == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('起始日期和截止日期不能为空')),
      );
      return;
    }

    // 验证截止日期是否晚于起始日期
    if (_editingItem.deadline!.isBefore(_editingItem.startDate!)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('截止日期必须晚于起始日期')),
      );
      return;
    }

    // 保持原有的pid
    final updatedItem = _editingItem.copyWith(
      pid: _editingItem.pid,  // 确保保留原有的pid
      title: _titleController.text,
      description: _descriptionController.text.isEmpty
          ? null
          : _descriptionController.text,
    );
    print('保存的DDL: ${updatedItem.toJson()}');
    
    // 更新到 AppDataManager
    await AppDataManager().updateDDL(updatedItem);
    
    // 更新本地状态
    setState(() {
      _editingItem = updatedItem;
      _isEditing = false;
    });
    
    // 通知父组件更新
    widget.onUpdate(updatedItem);
  }

  void _insertMarkdown(String start, String end) {
    final text = _descriptionController.text;
    final selection = _descriptionController.selection;
    
    // 确保选择范围有效
    if (selection.start < 0 || selection.end > text.length) {
      // 如果选择范围无效，就在当前位置插入
      final currentPosition = selection.baseOffset;
      final safePosition = currentPosition.clamp(0, text.length);
      final newText = text.substring(0, safePosition) + start + end + text.substring(safePosition);
      
      setState(() {
        _descriptionController.value = TextEditingValue(
          text: newText,
          selection: TextSelection.collapsed(
            offset: safePosition + start.length,
          ),
        );
      });
      return;
    }

    // 正常插入带有选中文本的情况
    final selectedText = text.substring(selection.start, selection.end);
    final newText = text.replaceRange(
      selection.start,
      selection.end,
      '$start$selectedText$end',
    );
    
    setState(() {
      _descriptionController.value = TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(
          offset: selection.start + start.length + selectedText.length + end.length,
        ),
      );
    });
  }

  void _insertImage() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920, // 限制图片最大宽度
        maxHeight: 1920, // 限制图片最大高度
      );
      
      if (image != null) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
        );

        final url = await _saveFileToLocal(File(image.path), 'img');
        Navigator.pop(context); // 关闭加载对话框

        if (url != null) {
          setState(() {
            _insertMarkdown('![图片](', '$url)');
          });
        }
      }
    } catch (e) {
      Navigator.pop(context); // 关闭加载对话框
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('插入图片失败: $e')),
      );
    }
  }

  void _insertAttachment() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? file = await picker.pickMedia();
      
      if (file != null) {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
        );

        final sourceFile = File(file.path);
        if (await sourceFile.length() > _maxFileSize) {
          Navigator.pop(context); // 关闭加载对话框
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('文件大小超过5MB限制')),
          );
          return;
        }

        final url = await _saveFileToLocal(sourceFile, 'attachment');
        Navigator.pop(context); // 关闭加载对话框

        if (url != null) {
          final fileName = file.name;
          final fileSize = await sourceFile.length();
          final sizeStr = _formatFileSize(fileSize);
          setState(() {
            _attachments.add(_AttachmentInfo(name: fileName, size: sizeStr, url: url));
          });
        }
      }
    } catch (e) {
      Navigator.pop(context); // 关闭加载对话框
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('插入附件失败: $e')),
      );
    }
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  void _insertCode() async {
    final result = await Navigator.of(context).push<Map<String, String>>(
      MaterialPageRoute(
        builder: (context) => CodeInputPage(languages: _programmingLanguages),
      ),
    );

    if (result != null) {
      final language = result['language'] ?? '';
      final code = result['code'] ?? '';
      if (code.isNotEmpty) {
        setState(() {
          _insertMarkdown(
            '\n```$language\n',
            '$code\n```\n',
          );
        });
      }
    }
  }

  Future<void> _showInsertLinkDialog() async {
    final textController = TextEditingController();
    final urlController = TextEditingController();
    final formKey = GlobalKey<FormState>();
    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('插入链接'),
          content: Form(
            key: formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextFormField(
                  controller: textController,
                  decoration: const InputDecoration(labelText: '链接文本'),
                  validator: (v) => v == null || v.isEmpty ? '请输入链接文本' : null,
                ),
                TextFormField(
                  controller: urlController,
                  decoration: const InputDecoration(labelText: '链接地址'),
                  validator: (v) => v == null || v.isEmpty ? '请输入链接地址' : null,
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (formKey.currentState!.validate()) {
                  final text = textController.text.trim();
                  final url = urlController.text.trim();
                  _insertMarkdown('[$text](', '$url)');
                  Navigator.pop(context);
                }
              },
              child: const Text('插入'),
            ),
          ],
        );
      },
    );
  }

  List<Widget> _buildAttachmentCards({bool editable = false}) {
    // 从描述中提取附件信息
    final attachments = <_AttachmentInfo>[];
    if (_editingItem.description != null && _editingItem.description!.isNotEmpty) {
      final attachmentPattern = RegExp(r'\[(.*?)\]\((file://.*?)\)');
      final matches = attachmentPattern.allMatches(_editingItem.description!);
      for (final match in matches) {
        final name = match.group(1)!;
        final url = match.group(2)!;
        attachments.add(_AttachmentInfo(
          name: name,
          size: '未知大小',
          url: url,
        ));
      }
    }

    // 合并当前编辑的附件和从描述中提取的附件
    final allAttachments = [..._attachments, ...attachments];

    return allAttachments.map((att) {
      return Card(
        margin: const EdgeInsets.symmetric(vertical: 4),
        child: ListTile(
          leading: const Icon(Icons.attach_file),
          title: Text(att.name),
          subtitle: Text(att.size),
          trailing: editable
              ? IconButton(
                  icon: const Icon(Icons.delete, color: Colors.red),
                  onPressed: () {
                    setState(() {
                      _attachments.remove(att);
                    });
                  },
                )
              : null,
          onTap: () async {
            try {
              final filePath = att.url.replaceFirst('file://', '');
              print('打开附件路径filePath: $filePath');
              final file = File(filePath);
              if (!await file.exists()) {
                throw '文件不存在';
              }
              
              final methodChannel = const MethodChannel('com.example.new_flutter_project_fixed/file');
              await methodChannel.invokeMethod('openFile', {
                'path': filePath,
                'mimeType': _getMimeType(filePath),
              });
            } catch (e) {
              if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('无法打开附件: $e')),
                );
              }
            }
          },
        ),
      );
    }).toList();
  }

  String _getMimeType(String filePath) {
    final extension = path.extension(filePath).toLowerCase();
    switch (extension) {
      case '.jpg':
      case '.jpeg':
        return 'image/jpeg';
      case '.png':
        return 'image/png';
      case '.pdf':
        return 'application/pdf';
      case '.doc':
        return 'application/msword';
      case '.docx':
        return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      case '.xls':
        return 'application/vnd.ms-excel';
      case '.xlsx':
        return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      case '.ppt':
        return 'application/vnd.ms-powerpoint';
      case '.pptx':
        return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
      case '.txt':
        return 'text/plain';
      case '.zip':
        return 'application/zip';
      case '.rar':
        return 'application/x-rar-compressed';
      default:
        return '*/*';
    }
  }
}

class _CodeHighlighter extends SyntaxHighlighter {
  @override
  TextSpan format(String source) {
    return TextSpan(
      children: [
        WidgetSpan(
          child: HighlightView(
            source,
            language: 'dart', // 可以根据代码块的语言动态设置
            theme: githubTheme,
            padding: const EdgeInsets.all(8),
          ),
        ),
      ],
    );
  }
}
